package cloud

import (
	"CloudInterface/common"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/util/gconv"
	"go.uber.org/zap"
	"io"
	"math/rand"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

// http://10.0.0.171:8084
// https://cmsapi.dolit.cn
const baseUrl = "http://10.0.0.171:8084"

var (
	RequestUserParam url.Values
	OriginalPostBody url.Values
)

type CloudClient struct {
	client http.Client
	//Writer *multipart.Writer
	ReqParams url.Values
}

// 获取请求客户端
func GetCloudClient(appKey, appSecret string) CloudClient {
	randStr := RandString(32)
	RequestUserParam, OriginalPostBody = requestPostKey(appKey, appSecret, randStr)
	tr := http.Transport{DisableKeepAlives: true}
	client := http.Client{Transport: &tr}

	cloudClient := CloudClient{
		client:    client,
		ReqParams: RequestUserParam,
	}
	return cloudClient
}

// 获得随机字符串
func RandString(len int) string {
	rand.Seed(time.Now().UnixNano())
	randBytes := make([]byte, len/2)
	rand.Read(randBytes)
	return fmt.Sprintf("%x", randBytes)
}

// Post请求客户密钥封装
func requestPostKey(appKey string, appSecret string, randStr string) (url.Values, url.Values) {
	requestTime := strconv.Itoa(int(time.Now().Unix()))
	sign := Md5Tool(appKey + Md5Tool(appSecret+"dolit-cloud-openapi-v1"+randStr) + requestTime)
	StaticBody := url.Values{}
	requestBody := url.Values{}
	//www-form格式
	requestBody.Set("app_key", appKey)
	requestBody.Set("rand_str", randStr)
	requestBody.Set("request_time", requestTime)
	requestBody.Set("sign", sign)

	StaticBody.Set("app_key", appKey)
	StaticBody.Set("rand_str", randStr)
	StaticBody.Set("request_time", requestTime)
	StaticBody.Set("sign", sign)

	return requestBody, StaticBody

}

// Get请求客户密钥封装
func requestGetKey(appKey string, appSecret string, randStr string) url.Values {
	requestTime := strconv.FormatInt(time.Now().Unix(), 10)
	sign := Md5Tool(appKey + Md5Tool(appSecret+"dolit-cloud-openapi-v1"+randStr) + requestTime)

	keys := url.Values{}
	keys.Set("app_key", appKey)
	keys.Set("rand_str", randStr)
	keys.Set("request_time", requestTime)
	keys.Set("sign", sign)
	return keys
}

// 解析Http请求的数据到结构体中
func DecodeData(body []byte, data *common.ResultData) {
	err := json.Unmarshal(body, data)
	if err != nil {
		zap.L().Error(err.Error())
	}
}

// 重新设置参数
func (CR *CloudClient) ResetPostParam(oldPost url.Values) {
	newPost := make(map[string][]string)
	for k, v := range oldPost {
		newPost[k] = v
	}
	CR.ReqParams = newPost
}

func Md5Tool(data string) string {
	t := md5.New()
	io.WriteString(t, data)
	return fmt.Sprintf("%x", t.Sum(nil))
}

// 解析用户参数
func (CR *CloudClient) SetParams(data interface{}) {
	jsonData, _ := json.Marshal(data)
	var jsonMap map[string]interface{}
	json.Unmarshal(jsonData, &jsonMap)
	for k, v := range jsonMap {
		CR.ReqParams.Set(k, gconv.String(v))
	}
}
